package vip.xianz.jobmanager.web.controller;

import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.xianz.jobmanager.data.entity.UserLoginLog;
import vip.xianz.jobmanager.data.entity.XUser;
import vip.xianz.jobmanager.data.vo.ResultBean;
import vip.xianz.jobmanager.exception.UsernamePasswordMistakeException;
import vip.xianz.jobmanager.service.IXUserService;
import vip.xianz.jobmanager.util.CheckUtils;
import vip.xianz.jobmanager.util.PrimaryKeyUtils;
import vip.xianz.jobmanager.util.SessionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.Instant;

/**
 * 登录注册控制：负责用户的登录注册与登出
 * @author submitX
 *
 */
@Controller
public class LoginRegistController {
	@Autowired
	private IXUserService userService;

	/**
	 * 登录请求
	 * @param userId
	 * @param password
	 * @return
	 */
	@PostMapping(value="/login")
	public @ResponseBody ResultBean<Boolean> login(HttpServletRequest request, String userId, String password) {
		XUser xUser = userService.getUserById(userId);
		if (xUser != null && xUser.getPassword().equals(password)) {
			request.getSession().setAttribute(SessionUtils.SESSION_USER_KEY, xUser);

			// 封装用户日志
			UserLoginLog log = new UserLoginLog();
			log.setLogId(PrimaryKeyUtils.UUID());
			UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
			log.setBrowser(userAgent.getBrowser().toString());
			log.setLoginTime(Instant.now());
			log.setOs(userAgent.getOperatingSystem().toString());
			log.setUserId(xUser.getUserId());
			log.setUserIp(request.getRemoteHost());
			// 更新用户登录信息
			userService.updateLoginAndRecoderLog(userId, log);
		} else {
			throw new UsernamePasswordMistakeException();
		}
		return new ResultBean<Boolean>(true);
	}

	/**
	 * 注册用户
	 * @param user 用户名(id)、密码和昵称
	 * @return
	 */
	@PostMapping(value = "/regist")
	public @ResponseBody ResultBean<Boolean> registUser(@Valid XUser user, BindingResult errors) {
        CheckUtils.notErrors(errors);
        // TODO: 等完成角色时再添加角色
        user.setCreateTime(Instant.now());
		return new ResultBean<Boolean>(userService.addUser(user));
	}
}
